<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from "vue";
import {reqHasTrademark, reqAddOrUpdateTrademark, reqDeleteTrademark} from "@/api/product/trademark";
import type {Trademark} from "@/api/product/trademark/type.ts";
import type {UploadProps} from "element-plus";
import {ElMessage} from "element-plus";

const currPage = ref<number>(1)
const pageSize = ref<number>(3)
const total = ref<number>(0)
const trademarkArr = ref<any>([])
const dialogVisible = ref<boolean>(false)
const title = ref('')
const formCom = ref()
const trademarkParams = reactive<Trademark>({
  tmName:'',
  logoUrl:''
})

const validatorTmName = (value:any, callback:any) => {
  if(value.trim().length >= 2) {
    callback()
  }else {
    callback(new Error('品牌名不符合要求'))
  }
}

const validatorLogoUrl = (value:any, callback:any) => {
  if(value) {
    callback()
  }else {
    callback(new Error('请上传文件'))
  }
}

// 表单校验
const rules = {
  tmName:[
    {
      required:true,
      trigger:'blur',
      validator:validatorTmName
    }
  ],
  logoUrl:[
    {
      required:true,
      trigger: '',
      validator:validatorLogoUrl
    }
  ]
}

const getHasTrademark = async () => {
  /*
  * total存储已有品牌数总数
  *
  * */
  const result = await reqHasTrademark(currPage.value, pageSize.value)
  console.log("src/views/product/trademark/index.vue:", result)
  if (result.code === 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
    if (trademarkArr.value && trademarkArr.value[0].tmName === '小米') {
      trademarkArr.value[0].logoUrl = "http://" + trademarkArr.value[0].logoUrl
    }
  }
}

onMounted(() => {
  getHasTrademark()
})

const changePageNum = () => {
  getHasTrademark()
}

const addTrademark = () => {
  dialogVisible.value = true
  title.value = '添加品牌'
  nextTick(()=>{
    formCom.value.clearValidate()
  })
  if (trademarkParams.id) trademarkParams.id = null
  trademarkParams.logoUrl = ''
  trademarkParams.tmName = ''
}

const editTrademark = (row:Trademark) => {
  dialogVisible.value = true
  title.value = '修改品牌'
  nextTick(()=>{
    formCom.value.clearValidate()
  })
  trademarkParams.id = row.id
  trademarkParams.tmName = row.tmName
  trademarkParams.logoUrl = row.logoUrl
}

const deleteTrademark = async (id:number) => {
  const result = await reqDeleteTrademark(id)
  console.log(result)
  if(result.code === 200) {
    ElMessage({
      type:'success',
      message:'删除品牌成功'
    })
  }else {
    ElMessage({
      type:'error',
      message:'删除品牌失败'
    })
  }
  await getHasTrademark()
}


// 点击确定后发送请求添加品牌
const confirm = async () => {
  await formCom.value.validate()
  const result = await reqAddOrUpdateTrademark(trademarkParams)
  if(result.code === 200) {
    dialogVisible.value = false
    ElMessage({
      type:'success',
      message:trademarkParams.id ? '修改成功' :'添加成功'
    })
    if(!trademarkParams.id) currPage.value = 1
    await getHasTrademark()
  }else {
    ElMessage({
      type:'error',
      message:trademarkParams.id ? '修改失败' : '添加失败'
    })
  }
}

const cancel = () => {
  dialogVisible.value = false
}

// 上传图片组件，上传前触发的钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  if(rawFile.type === 'image/png' || rawFile.type === 'image/jpeg' || rawFile.type === 'image/gif' || rawFile.type === 'image/jpg') {
    if(rawFile.size/1024/1024 < 4) {
      return true
    }else {
      ElMessage({
        type:'error',
        message:'上传的文件大小应小于4MB'
      })
      return false
    }
  }else {
    ElMessage({
      type:'error',
      message:'图片扩展名不正确'
    })
    return false
  }
}

// 上传成功后的钩子
const handleAvatarSuccess:UploadProps["onSuccess"] = (response) => {
  trademarkParams.logoUrl = response.data
  formCom.value.clearValidate()
}
</script>

<template>
  <div>
    <!-- 内容展示 -->
    <el-card class="box-card" style="">
      <!--      添加按钮-->
      <el-button type="primary" size="default" @click="addTrademark">添加品牌</el-button>
      <el-table style="margin: 10px 0" :border="true" :data="trademarkArr">
        <el-table-column label="序号" width="100px" type="index" align="center"></el-table-column>
        <el-table-column label="品牌名称">
          <!--          row即为el-table中的data属性保存的数据， $index就是该数组索引-->
          <template v-slot="{row}">
            <pre>{{ row.tmName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌Logo" align="center">
          <template v-slot="{row}">
            <img :src="row.logoUrl" style="width: 170px;" alt="加载失败">
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template v-slot="{row}">
            <el-button type="primary" size="large" icon="Edit" @click="editTrademark(row)"></el-button>
            <el-popconfirm
                :title="`你确定要删除${row.tmName}吗？`"
                width="200px" icon="Delete" icon-color="red"
                @confirm="deleteTrademark(row.id)">
              <template v-slot:reference>
                <el-button type="primary" size="large" icon="Delete" color="#c12127"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!--分页器
          pagination
            v-model:current-page:设置分页器当前页码
            v-model:page-size：每页显示条数
            page-sizes:用于设置下拉菜单数据
      -->
      <el-pagination @current-change="changePageNum"
                     v-model:current-page="currPage"
                     v-model:page-size="pageSize"
                     :page-sizes="[3,5,7,9,40]"
                     :background="true"
                     @size-change="changePageNum"
                     layout="prev, pager, next, jumper, ->, sizes, total"
                     :total="total"
                     :hide-on-single-page="true"/>
    </el-card>
    <!-- 会话框组件-->
    <!--  v-model默认控制显示与隐藏  -->
    <el-dialog
        v-model="dialogVisible"
        :title="title"
        style="height: 500px">
      <el-form :model="trademarkParams" :rules="rules" style="width: 80%" ref="formCom">
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input placeholder="品牌名称" v-model="trademarkParams.tmName"/>
        </el-form-item>
        <el-form-item label="品牌Logo" label-width="100px" prop="logoUrl">
          <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="trademarkParams.logoUrl" style="height: 250px;width: 100%" :src="trademarkParams.logoUrl" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button type="primary" size="default" style="border: 1px solid #dcdfe6" color="white" @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 250px;
  height: 250px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: #2b2d30;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>